import {
  message,
  Modal,
  Row,
  Col,
  Timeline,
  Select,
  BackTop,
  Button,
  Skeleton,
} from 'antd'
import { QuestionCircleOutlined } from '@ant-design/icons'
import React, { useEffect, useState } from 'react'
import { RouteComponentProps } from 'react-router-dom'
import CommonBackground from '../../components/CommonBackground'
import CustomizedTabInfo from '../../components/CustomizedTabInfo'
import TabInfo from '../../components/TabInfo'
import { addTab } from './tabAPI'
import { delTabCollection, moveTabCollection } from './tabCollectionAPI'
import {
  getWorkSpaceBaseInfo,
  getWorkSpaceDetail,
  WorkspaceBaseInfo,
  WorkspaceDetail,
} from './workspaceAPI'

interface MatchParams {
  wid: string
}

const WorkspaceDetailPage: React.FC<
  RouteComponentProps<MatchParams>
> = props => {
  const [detail, setDetail] = useState<WorkspaceDetail | null | undefined>(null)

  //Modal的打开
  const [visible, setVisible] = React.useState(false)
  //loading的开启
  const [confirmLoading, setConfirmLoading] = React.useState(false)
  //当前的workspace信息
  const [workspaces, setWorkSpaces] = useState<WorkspaceBaseInfo[]>([])
  //option的选中值
  const [curSelectedOption, setCurSelectedOption] = useState<string | null>(
    null,
  )
  // tabCollection的选中值
  const [curSelectedTabs, setCurSelectedTabs] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)

  // 移动Tab集合模块中的Select
  const { Option } = Select
  // 回到顶部BackTop的样式Style
  const style = {
    height: 40,
    width: 40,
    lineHeight: '40px',
    borderRadius: 4,
    backgroundColor: '#1DA57A',
    color: '#fff',
    textAlign: 'center',
    fontSize: 14,
  }

  useEffect(() => {
    _fetchWorkSpaceDetailAndSet()
  }, [])

  // 拉取workspaceDetail的数据
  const _fetchWorkSpaceDetailAndSet = async () => {
    try {
      const res = await getWorkSpaceDetail(props.match.params.wid)
      setDetail(res.data.data)
      setLoading(false)
    } catch (error) {
      message.error('拉取数据出错，请重试')
    }
  }

  //拉取workspace的信息用于选择移动到的workspace
  const _fetchWorkSpaceInfoAndSet = async () => {
    try {
      const result = await getWorkSpaceBaseInfo()
      const data = result.data.data
      if (data) {
        setWorkSpaces(data)
      }
    } catch (error) {
      message.error('拉取数据出错，请重试')
    }
  }

  // 删除对应的TabCollection
  const onDelTabCollection = async (delTabsId: string) => {
    try {
      if (!delTabsId) return
      const _ = await delTabCollection(delTabsId)
      _fetchWorkSpaceDetailAndSet()
    } catch (error) {
      message.error('删除失败，请稍后重试')
    }
  }

  //提交打开Modal的表单
  const onOpenModal = () => {
    _fetchWorkSpaceInfoAndSet()
    setVisible(true)
  }

  //设置选中的Option的值
  const handleSelectChange = (selVal: string) => {
    setCurSelectedOption(selVal)
  }

  //当点击Modal里面的OK的时候，如何处理
  const handleOk = async () => {
    setConfirmLoading(true)
    if (curSelectedTabs && curSelectedOption) {
      await moveTabCollection(curSelectedTabs, curSelectedOption)
    }
    await _fetchWorkSpaceDetailAndSet()
    setConfirmLoading(false)
    setVisible(false)
    reset()
  }

  //点击Modal里面的cancel的时候如何处理
  const handleCancel = () => {
    setVisible(false)
    reset()
  }

  //重制选择的Option值和Tab值
  const reset = () => {
    setCurSelectedOption(null)
    setCurSelectedTabs(null)
  }

  //设置当前的TabCollection的值
  const onSelectCollection = (value: string) => {
    setCurSelectedTabs(value)
  }
  const [isHelpModalVisible, setIsHelpModalVisible] = useState(false)

  const showHelpModal = () => {
    setIsHelpModalVisible(true)
  }

  const handleHelpOk = () => {
    setIsHelpModalVisible(false)
  }

  const handleHelpCancel = () => {
    setIsHelpModalVisible(false)
  }
  //设置drag的接受数据的函数
  const handleDrop = async (e: any) => {
    const tabInfo = JSON.parse(e.dataTransfer.getData('text/plain'))
    const id = detail?.customedTabsInfo[0].id
    if (id) {
      await addTab(tabInfo, id)
      await _fetchWorkSpaceDetailAndSet()
    }
  }

  function handleDragOver(e: any) {
    e.preventDefault()
  }

  return (
    <CommonBackground title={detail?.name}>
      <div style={{ padding: '20px' }}>
        <Row>
          <Col span={13}>
            <Timeline mode={'left'} reverse>
              <Skeleton loading={loading} active>
                {detail?.tabsInfo.map(item => (
                  // label={_getTimeStr(item.createTime)}
                  <Timeline.Item>
                    <TabInfo
                      {...item}
                      onDel={onDelTabCollection}
                      onSelect={onSelectCollection}
                      onOpenModal={onOpenModal}
                      key={item.id}
                    ></TabInfo>
                  </Timeline.Item>
                ))}
              </Skeleton>
            </Timeline>
          </Col>
          <Col span={11} onDragOverCapture={handleDragOver} onDrop={handleDrop}>
            <div>
              <h1>
                收纳箱
                <Button
                  type="link"
                  size="large"
                  style={{ color: '#000', fontSize: '20px' }}
                  onClick={showHelpModal}
                >
                  <QuestionCircleOutlined />
                </Button>
                <Modal
                  title="帮助"
                  visible={isHelpModalVisible}
                  footer={[
                    <Button key="back" onClick={handleHelpOk}>
                      确定
                    </Button>,
                  ]}
                >
                  <p>
                    收纳箱可根据您的自定义需求，容纳从左侧标签页集合中拖拽过来的标签页。
                  </p>
                </Modal>
              </h1>
              <Skeleton loading={loading} active>
                {detail?.customedTabsInfo.map(item => (
                  <CustomizedTabInfo
                    {...item}
                    key={item.id}
                  ></CustomizedTabInfo>
                ))}
              </Skeleton>
            </div>
          </Col>
        </Row>
      </div>
      <Modal
        title="请选择移动到的workspace"
        visible={visible}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
      >
        <Select style={{ width: 120 }} onChange={handleSelectChange}>
          {workspaces.map(item => (
            <Option value={item._id}>{item.name}</Option>
          ))}
        </Select>
      </Modal>
      <BackTop>
        <div>UP</div>
      </BackTop>
    </CommonBackground>
  )
}

export default WorkspaceDetailPage
